package cn.zyy.jdbc;

import cn.zyy.entity.Usr;
import cn.zyy.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * 模拟用户的登录注册
 */
public class JDBCDemo01 {
    public static void main(String[] args) {
        //register();
        login();
    }
    //用户注册
    public static void register() {
        Scanner scanner = new Scanner(System.in);
        //获取用户名
        System.out.println("请输入用户名：");
        String username = scanner.nextLine();
        //获取密码
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        //获取用户的生日
        System.out.println("请输入生日(1990-02-03)：");
        String birth = scanner.nextLine();
        //创建时间
        Date createDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(createDate);
        //使用jdbc进行数据的持久化操作  usr
        Connection conn = JDBCUtil.getConnection();
        //获取操作数据库的对象  stmt
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            String sql = "insert into usr(username,password,birth,create_time) values('"+username+"','"+password+"','"+birth+"','"+format+"')";
            int line = stmt.executeUpdate(sql);
            //判定注册结果
            System.out.println(line>0?"成功":"失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {//释放资源
            JDBCUtil.closeAll(null,stmt,conn);
        }
    }
    //用户登录
    public static void login() {
        Scanner scanner = new Scanner(System.in);
        //获取用户名
        System.out.println("请输入用户名：");
        String username = scanner.nextLine();
        //获取密码
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        //使用jdbc进行数据的查询操作  username password
        Connection conn = JDBCUtil.getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            String sql = "select username,password from usr where username = '"+username+"' and password = '"+password+"'";
            rs = stmt.executeQuery(sql);
            //处理结果集
            Usr usr = null;
            while(rs.next()) {
                String uname = rs.getString(1);
                String pwd = rs.getString(2);
                usr = Usr.builder().username(uname).password(pwd).build();
            }
            //处理登录的结果
            if (usr != null) {
                System.out.println("登录成功！");
            }else {
                System.out.println("登陆失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.closeAll(rs,stmt,conn);
        }
    }


}
